package services

import (
	"errors"
	"gorm.io/gorm"
	"server/global"
	"server/internal/model"
	"server/utils/tools"
	"time"
)

var User = new(user)

type user struct {
	model.User
	GroupName  string `json:"group_name"`
	TissueName string `json:"tissue_name"`
	Qrcode     string `json:"qrcode"`
}

// GetList 列表
func (a user) GetList(Db *gorm.DB) ([]user, int64) {
	var list []user
	var total int64
	Db.Model(&a.User).
		Select("user.*,(select name from user_group where id = user.group_id) as group_name").
		//Order("user.create_time desc").
		Find(&list).Offset(-1).Count(&total)
	for k, v := range list {
		if v.GroupId == 0 {
			list[k].GroupName = "普通用户"
		}
	}
	return list, total
}

// GetById 单条
func (a user) GetById(id any) user {
	Db := global.GL_DB
	detail := user{}
	Db.Model(&a.User).
		Select("user.*,(select name from user_group where id = user.group_id) as group_name").
		Where("id =?", id).First(&detail)
	detail.Password = ""

	return detail

}

// Create 新增
func (a user) Create(data model.User) (model.User, error) {
	Db := global.GL_DB
	err := Db.Transaction(func(tx *gorm.DB) error {

		if data.Username != "" {
			detail := user{}
			tx.Model(&data).Where("username =?", data.Username).First(&detail)
			if detail.ID > 0 {
				return errors.New("用户已存在")
			}
		}

		t := time.Now()
		data.CreateTime = int(t.Unix())
		data.UpdateTime = int(t.Unix())
		if data.Password != "" {
			data.Password = tools.GetMd5String(data.Password)
		}

		//创建用户
		if err := tx.Create(&data).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}

		//userMoney := UserMoney{}
		//userMoney.UserID = a.ID
		//userMoney.Balance = 0.00
		//userMoney.Status = "1"
		////创建钱包
		//if err := tx.Create(&userMoney).Error; err != nil {
		//	// 返回任何错误都会回滚事务
		//	return err
		//}

		// 返回 nil 提交事务
		return nil
	})

	return data, err
}

// Update 编辑
func (a user) Update(data model.User) (model.User, error) {
	Db := global.GL_DB
	detail := user{}
	if data.Username != "" {
		Db.Model(&data).
			Where("username =? and id <> ?", data.Username, data.ID).First(&detail.User)
		if detail.ID > 0 {
			return data, errors.New("用户名重复")
		}
	}

	//if data.Password != "" {
	//	Db = Db.Select("group_id", "name", "id_card", "avatar", "mobile", "password")
	//} else {
	//	Db = Db.Select("group_id", "name", "id_card", "avatar", "mobile")
	//}

	t := time.Now()
	data.UpdateTime = int(t.Unix())
	return data, Db.Updates(&data).Error

}

// Delete 删除
func (a user) Delete(ids []int) error {
	Db := global.GL_DB
	return Db.Delete(&a.User, ids).Error

}
